package cn.javablog.shiro;

import cn.javablog.common.lang.Result;
import cn.javablog.util.JwtUtils;
import cn.javablog.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends AuthenticatingFilter{
    @Value("${blog.jwt.expire}")
    private String expire;
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        // 获取token
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwt = request.getHeader("Authorization");
        if(StringUtils.isEmpty(jwt)){
            return null;
        }
        return new JwtToken(jwt);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        // 获取token
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwt = request.getHeader("Authorization");
        if(StringUtils.isEmpty(jwt)){
            return true;
        }else{
            Object objName = redisUtil.get(jwt);
            if(null==objName){
                handler401(servletResponse, 401, "token已失效，请重新登录",null);
                return false;
            }
            Object token = redisUtil.get(String.valueOf(objName));
            if(!String.valueOf(token).equals(jwt)){
                handler401(servletResponse, 401, "token已失效，请重新登录",null);
                return false;
            }
            redisUtil.set(jwt,String.valueOf(objName),Long.valueOf(expire));
            redisUtil.set(String.valueOf(objName),jwt,Long.valueOf(expire));
            // 校验jwt
//            Claims claims = jwtUtils.getClaimByToken(jwt);
//            if(claims==null||jwtUtils.isTokenExpired(claims.getExpiration())||!jwtUtils.comparisonToken(jwt)){
//                handler401(servletResponse, 401, "token已失效，请重新登录",null);
//                return false;
//            }
            //检测登陆
            return executeLogin(servletRequest,servletResponse);
        }
    }
    /**
     * token有问题
     * @param response
     * @param code
     * @param msg
     * @param data
     */
    private void handler401(ServletResponse response, int code, String msg,Object data) throws Exception{
        try {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setStatus(HttpStatus.OK.value());
            httpResponse.setContentType("application/json;charset=utf-8");
            Result fail = new Result().fail(code, msg, data);
            String str = JSON.toJSONString(fail, SerializerFeature.WriteMapNullValue);
            httpResponse.getWriter().write(str);
//            httpResponse.getWriter().write("{\"code\":" + code + ", \"msg\":\"" + msg + "\", \"data\":" + data + "}");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        JwtToken jwtToken = (JwtToken) token;
        try{
            Throwable throwable = e.getCause()==null?e:e.getCause();
            Result result = Result.fail(throwable.getMessage());
            String json = JSON.toJSONString(result);
            httpResponse.getWriter().println(json);
        }catch(IOException ioException){

        }
        return false;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
